<template>
  <div class="quarterAnalysis">
    <span class="mr-8">年份</span>
    <el-date-picker
      class="update-el-date mr-8"
      v-model="requestData.year"
      format="yyyy"
      value-format="yyyy"
      type="year"
      @change="changeDate"
      placeholder="选择日期"
    >
    </el-date-picker>
    <span class="mr-8">季度</span>

    <el-select
      v-model="requestData.quarter"
      @change="changeQuarter"
      placeholder="请选择"
    >
      <el-option
        v-for="item in quarterList"
        :key="item.id"
        :label="item.value"
        :value="item.id"
      >
      </el-option>
    </el-select>
    <div class="info_wrap">
      <div class="info_item">
        <div class="title">{{ quarterList[activeIndex - 1].value }}指标</div>
        <div class="number">{{ performanceAnalysisList.sellTarget }}</div>
      </div>
      <div class="info_item">
        <div class="title">{{ quarterList[activeIndex - 1].value }}业绩</div>
        <div class="number">
          {{ performanceAnalysisList.salesAmount }}
        </div>
      </div>
      <div class="info_item">
        <div class="title">环比</div>
        <div class="number_red">{{ performanceAnalysisList.chainRatio }}%</div>
      </div>
      <div class="info_item">
        <div class="title">
          {{ quarterList[activeIndex - 1].value }}业绩达成率
        </div>
        <div class="number">{{ performanceAnalysisList.achievementRate }}%</div>
      </div>
      <div class="info_item">
        <div class="title">
          {{ quarterList[activeIndex - 1].value }}指标缺口
        </div>
        <div class="number_red">{{ performanceAnalysisList.rabbet }}</div>
      </div>
    </div>
    <div class="echarts_wrap">
      <div class="titrle_wrap">
        <div>
          <span class="item color_1"></span>
          <span>销售目标</span>
        </div>
        <div>
          <span class="item color_2"></span>
          <span>销售业绩</span>
        </div>
        <div>
          <span class="item color_3"></span>
          <span>达成率</span>
        </div>
      </div>
      <div class="rate_wrap" :style="{ width: leftEchartWidth + 'px' }">
        <!-- 第一季度 -->
        <template v-if="requestData.quarter === 1">
          <div class="item_1">
            <div class="rate">{{ seriesData[0] }}%</div>
            <div class="rate_1"></div>
          </div>
        </template>
        <!-- 第二季度 -->
        <template v-if="requestData.quarter === 2">
          <div class="rate_item_wrap">
            <div class="rate_item item_2">
              <div class="rate">{{ seriesData[0] || 0 }}%</div>
              <div class="rate_1"></div>
            </div>
            <div class="rate_item item_3">
              <div class="rate">{{ seriesData[1] || 0 }}%</div>
              <div class="rate_1"></div>
            </div>
          </div>
        </template>
        <!-- 第三季度 -->
        <template v-if="requestData.quarter === 3 || requestData.quarter === 4">
          <div class="rate_item_wrap">
            <div class="rate_item item_4">
              <div class="rate">{{ seriesData[0] || 0 }}%</div>
              <div class="rate_1"></div>
            </div>
            <div class="rate_item item_5">
              <div class="rate">{{ seriesData[1] || 0 }}%</div>
              <div class="rate_1"></div>
            </div>
            <div class="rate_item item_6">
              <div class="rate">{{ seriesData[2] || 0 }}%</div>
              <div class="rate_1"></div>
            </div>
          </div>
        </template>
      </div>
      <div class="null_data_o" v-show="achievementRateList.length === 0">
        暂时数据
      </div>
      <div
        id="leftEcharts"
        style="width: 800px; height: 400px; margin-top: 30px"
        ref="leftEchartRef"
      ></div>
      <!-- <div
        id="rightEcharts"
        style="width: 800px; height: 400px; margin-top: 30px"
      ></div> -->
      <div class="null_data_one" v-if="performanceChartList.length === 0">
        暂无数据
      </div>
      <div
        v-if="requestData.quarter === 1"
        id="right_Echarts_fei"
        style="width: 800px; height: 400px; margin-top: 30px"
      ></div>
      <div
        v-if="requestData.quarter === 2"
        id="right_Echarts_fei"
        style="width: 800px; height: 400px; margin-top: 30px"
      ></div>
      <div
        v-if="requestData.quarter === 3"
        id="right_Echarts_fei"
        style="width: 800px; height: 400px; margin-top: 30px"
      ></div>
      <div
        v-if="requestData.quarter === 4"
        id="right_Echarts_fei"
        style="width: 800px; height: 400px; margin-top: 30px"
      ></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { quarterPerformanceAnalysis } from '@/request/store/K_PerformanceAnalysis'
import { getCurrentMonthFirst, deepClone } from '@/util/util'
export default {
  name: 'QuarterAnalysis',
  data() {
    return {
      yearList: [],
      myLegend: {
        data: []
      },
      myChart: '',
      // 数组的数据
      firstDataList: [],
      secondDataList: [],
      threeDataList: [],
      quarter: 1,
      activeIndex: 1,
      performanceAnalysisList: [],
      achievementRateList: [], // 业绩达成率
      performanceChartList: [], // 业绩走势图
      requestData: {
        year: '',
        quarter: 1
      },
      quarterList: [
        {
          id: 1,
          value: '一季度'
        },
        {
          id: 2,
          value: '二季度'
        },
        {
          id: 3,
          value: '三季度'
        },
        {
          id: 4,
          value: '四季度'
        }
      ],
      leftOption: {
        title: {
          text: '季度业绩达成率'
        },
        calculable: true,
        xAxis: {
          type: 'category',
          data: [],
          axisTick: {
            alignWithLabel: true
          }
        },

        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '销售目标',
            type: 'bar',
            data: [],
            color: '#017aff',
            label: {
              normal: {
                show: true, //显示数字
                position: 'top', //这里可以自己选择位置
                color: '#000',
                formatter: (params) => {
                  let result = [],
                    counter = 0,
                    num = params.data
                  num = (num || 0).toString().split('')
                  for (let i = num.length - 1; i >= 0; i--) {
                    counter++
                    result.unshift(num[i])
                    if (!(counter % 3) && i != 0) {
                      result.unshift(',')
                    }
                  }
                  result = result.join('')
                  return result
                }
              }
            }
            // markLine: {
            //   data: [
            //     {
            //       type: 'average'
            //     }
            //   ],
            //   color: '#f19149',
            //   animation: false,
            //   silent: false
            // }
          },
          // {
          //   symbolSize: 15,
          //   data: [
          //     // x y
          //     [11.0, 8.33],
          //     [1.0, 5]
          //   ],
          //   type: 'scatter',
          //   color: '#f19149'
          // },
          // {
          //   name: '达成率',
          //   data: [],
          //   type: 'line',
          //   color: '#f19149'
          // },
          {
            name: '销售业绩',
            type: 'bar',
            data: [],
            color: '#67afff',
            label: {
              normal: {
                show: true, //显示数字
                position: 'top', //这里可以自己选择位置
                color: '#000',
                formatter: (params) => {
                  let result = [],
                    counter = 0,
                    num = params.data
                  num = (num || 0).toString().split('')
                  for (let i = num.length - 1; i >= 0; i--) {
                    counter++
                    result.unshift(num[i])
                    if (!(counter % 3) && i != 0) {
                      result.unshift(',')
                    }
                  }
                  result = result.join('')
                  return result
                }
              }
            }
            // markLine: {
            //   data: [
            //     {
            //       type: 'average'
            //     }
            //   ],
            //   color: '#f19149',
            //   animation: false,
            //   silent: false
            // }
          }
        ]
      },
      rightOption: {
        title: {
          text: '业绩走势图'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: []
        },
        calculable: true,
        xAxis: [
          {
            type: 'category',
            data: []
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '',
            type: 'bar',
            data: [],
            color: '#b2d7ff'
          },
          {
            name: '',
            type: 'bar',
            data: [],
            color: '#67afff'
          },
          {
            name: '',
            type: 'bar',
            data: [],
            color: '#017aff'
          }
        ]
      },
      leftEchartWidth: 800,
      seriesData: []
    }
  },
  created() {
    let year = getCurrentMonthFirst(false)
    // console.log(year, '1000')
    this.requestData.year = year && year.split('-')[0]
    this.quarterPerformanceAnalysis(this.requestData)
    // console.log(this.requestData)
  },
  updated() {
    this.$nextTick(() => {
      this.createRight_oneEchart()
    })
  },
  methods: {
    // 季度输入框chage的时候，触发的函数
    async quarterPerformanceAnalysis(requestData) {
      const { data } = await quarterPerformanceAnalysis(requestData)
      console.log(data, '季度业绩的data')
      if (data && data.code === 200) {
        this.quarter = data.data.quarter

        // 截取数据
        if (this.myChart) {
          this.myChart.clear()
        }
        this.yearList = []
        this.firstDataList = []
        this.secondDataList = []
        this.threeDataList = []

        if (data.data.performanceChartList.length !== 0) {
          data.data.performanceChartList[0].map((item) => {
            this.yearList.push(item.year)
          })
        }

        // 遍历返回来的数组(倒序后端的数据)
        data.data.performanceChartList.reverse()
        for (const itemList of data.data.performanceChartList) {
          if (itemList && itemList.length !== 0) {
            this.firstDataList.push(itemList[2].salesAmount)
            this.secondDataList.push(itemList[1].salesAmount)
            this.threeDataList.push(itemList[0].salesAmount)
          }
        }
        this.performanceAnalysisList = data.data
        this.achievementRateList = data.data.achievementRateList
        // 业绩走势图数据
        this.performanceChartList = data.data.performanceChartList

        // this.setRightOption()
        this.setLeftOption()
      }
    },
    // 右边图标的方法
    createRight_oneEchart() {
      let chartDom = document.getElementById('right_Echarts_fei') // 指定图表的配置项和数据
      this.myChart = echarts.init(chartDom)
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        title: {
          text: '业绩走势图'
        },
        // 图例
        legend: {
          //配置legend，这里的data，要对应type为‘bar’的series数据项的‘name’名称，作为图例的说明
          // data: ['2019', '2020', '2021']
          data: this.yearList
        },
        calculable: true,
        xAxis: [
          {
            type: 'category',
            data:
              this.quarter === 1
                ? ['一季度']
                : this.quarter === 2
                ? ['一季度', '二季度']
                : this.quarter === 3
                ? ['一季度', '二季度', '三季度']
                : this.quarter === 4
                ? ['二季度', '三季度', '四季度']
                : [],
            // data: this.currentArr,
            // 去掉x轴
            axisLine: {
              show: false
            },
            // 去掉刻度线
            axisTick: {
              show: false
            },
            // 去掉网格
            splitLine: {
              show: false
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            show: true,
            // offset: 50
            axisLabel: {
              show: true,
              interval: 'auto',

              // formatter: '{value} %'
              formatter: function (val) {
                // if (val === 0 || val === 50 || val === 100) {
                // return val + '%'
                return val
                // }
              }
            },
            realtimeSort: false,
            // 去掉y轴
            axisLine: {
              show: false
            },
            // 去掉刻度线
            axisTick: {
              show: false
            },
            // 显示x轴的网格
            splitLine: {
              show: true
            }
          }
        ],
        // 关于柱子的样式，都在这里配置
        series: [
          // 一个对象代表一个柱子，这个柱子都是在这个对象配置
          // {
          //   name: '2019',
          //   type: 'bar',
          //   data: [78, 80, 87, 93],
          //   color: '#b2d7ff'
          // },
          {
            // name: '2019',
            name: this.yearList[2],
            type: 'bar',
            // all第一根柱子的数组
            // data: [120, 70, 60],
            data: this.firstDataList,
            // data: this.jin_xiao_moneyList[0],
            color: '#B2D7FF',
            barCategoryGap: '30%',
            // 设置百分比
            itemStyle: {
              normal: {
                label: {
                  show: true, //开启显示
                  position: 'top', //在上方显示
                  formatter: function (val) {
                    if (val.value !== 0) {
                      // return val.value + '%'
                      return val.value
                    } else {
                      return ''
                    }
                  },
                  textStyle: {
                    //数值样式
                    color: '#1a1a1a',
                    fontSize: 12
                  }
                }
              }
            }
          },
          {
            // name: '2020',
            // name: this.yearList[1],
            name: this.yearList[1],

            type: 'bar',
            // 数据源(增多一组)
            // all第二根柱子的数组
            // data: [90, 77, 62],
            data: this.secondDataList,

            color: '#67AFFF',
            barCategoryGap: '30%',
            // 设置头部数据
            itemStyle: {
              normal: {
                label: {
                  show: true, //开启显示
                  position: 'top', //在上方显示
                  formatter: function (val) {
                    if (val.value !== 0) {
                      // return val.value + '%'
                      return val.value
                    } else {
                      return ''
                    }
                  },
                  textStyle: {
                    //数值样式
                    color: '#1a1a1a',
                    fontSize: 12
                  }
                }
              }
            }
          },
          {
            // name: '2021',
            name: this.yearList[0],
            // name: this.yearList[0],

            type: 'bar',
            // 数据源(增多一组)
            // all第三根柱子的数组
            // data: [90, 77, 62],
            data: this.threeDataList,
            // data: this.jin_xiao_moneyList[1],
            // 深蓝色
            color: '#017AFF',
            barCategoryGap: '30%',
            // 设置百分比
            itemStyle: {
              normal: {
                label: {
                  show: true, //开启显示
                  position: 'top', //在上方显示
                  formatter: function (val) {
                    if (val.value !== 0) {
                      // return val.value + '%'
                      return val.value
                    } else {
                      return ''
                    }
                  },
                  textStyle: {
                    //数值样式
                    color: '#017AFF',
                    fontSize: 12
                  }
                }
              }
            }
          }
        ]
      }

      this.myChart.setOption(option)
    },
    createLeftEchart() {
      let leftColumn = this.$echarts.init(
        document.getElementById('leftEcharts')
      )
      leftColumn.setOption(this.leftOption)
    },
    setLeftOption() {
      let quarterList = deepClone(this.quarterList)
      let option = deepClone(this.leftOption)
      let seriesData = deepClone(this.seriesData)
      let achievementRateList = deepClone(this.achievementRateList)
      let xAxiData = option.xAxis.data
      let series = option.series
      achievementRateList.forEach((item, index) => {
        if (item && item.year) {
          // 季度的id
          let quarterIndex = item.quarter
          let year = item.year
          quarterList.forEach((it, ind) => {
            if (it.id === quarterIndex) {
              let xAxiDataName = `${year}第${it.value}`
              xAxiData.push(xAxiDataName)
            }
          })

          let achievementRate = item.achievementRate

          series[0].data.push(item.sellTarget)
          seriesData.push(achievementRate)
          series[1].data.push(item.salesAmount)
        }
      })
      this.leftOption = option
      this.seriesData = seriesData
      this.createLeftEchart()
    },

    // // 设置 右侧图表
    // setRightOption() {
    //   let quarterList = this.quarterList // 季度名称
    //   let quarterNameArr = [] // 保存临时的名称
    //   let quarterYearArr = [] // 保存临时的月份
    //   let serieItem = {}
    //   let option = deepClone(this.rightOption) // 右侧图表配置
    //   let performanceChartList = deepClone(this.performanceChartList) // 数据
    //   for (let i = 0; i < performanceChartList.length; i++) {
    //     let itemDetailList = performanceChartList[i]
    //     // 判断是否拿到数据
    //     if (itemDetailList) {
    //       // 设置底部文字，根据索引值拿到 quarterList 的季度名
    //       let quarterIndex = itemDetailList[i] && itemDetailList[i].quarter
    //       let quarterName = quarterList[quarterIndex - 1].value
    //       let year = itemDetailList[i] && itemDetailList[i].year
    //       quarterNameArr.push(quarterName)
    //       quarterYearArr.push(year)
    //       option.xAxis[0].data = quarterNameArr
    //       option.legend.data = quarterYearArr
    //       console.log(option.legend.data, 'itemDetailList')
    //       // for (let j = 0; j < quarterList.length; j++) {
    //       //   const isFlg =
    //       //     itemDetailList[j] &&
    //       //     quarterList[j].id === itemDetailList[j].quarter
    //       //   if (isFlg) {
    //       //     console.log(itemDetailList[j])
    //       //   }
    //       // }
    //       this.rightOption = option
    //       // this.createRightEchart()
    //     }
    //   }
    // },

    /*
    createRightEchart() {
      let myChart = this.$echarts.init(document.getElementById('rightEcharts'))
      myChart.setOption(this.rightOption)
    },
    */

    // 季度选择
    changeQuarter(e) {
      this.activeIndex = e
      this.Empty()
      this.quarterPerformanceAnalysis(this.requestData)
    },
    // 时间选择
    changeDate(date) {
      this.requestData.year = date
      this.Empty()
      this.quarterPerformanceAnalysis(this.requestData)
    },
    // 清空
    Empty() {
      let leftOption = deepClone(this.leftOption) // 左侧图表配置
      let rightOption = deepClone(this.rightOption) // 右侧图表配置
      let seriesData = deepClone(this.seriesData)
      leftOption.series[0].data = []
      leftOption.series[1].data = []
      seriesData = []
      // leftOption.series[2].data = []
      leftOption.xAxis.data = []

      rightOption.series[0].data = []
      rightOption.xAxis.data = []
      this.seriesData = seriesData
      this.leftOption = leftOption
      this.rightOption = rightOption
    }
  },
  mounted() {
    this.createLeftEchart()
    this.leftEchartWidth = this.$refs.leftEchartRef.clientWidth
  }
}
</script>

<style lang="less" scoped>
.null_data_one {
  position: absolute;
  top: 200px;
  left: 1200px;
}
.null_data_o {
  position: absolute;
  top: 200px;
  left: 400px;
}
.quarterAnalysis {
  /deep/ .el-select {
    .el-input {
      .el-input__inner {
        height: 32px;
      }
      .el-select__caret {
        line-height: 27px;
      }
    }
  }
  .info_wrap {
    display: flex;
    justify-content: space-around;
    align-items: center;
    text-align: center;
    margin-top: 16px;
    height: 120px;
    border-radius: 10px;
    background-color: #f7f7f7;
    .info_item {
      // width: 120px;
      height: 80px;
      .title {
        margin-top: 13px;
        color: #959595;
      }
      .number {
        font-weight: 700;
        font-size: 20px;
        color: #017aff;
      }
      .number_red {
        font-weight: 700;
        font-size: 20px;
        color: #fb4d4d;
      }
    }
  }
  .echarts_wrap {
    margin-top: 50px;
    position: relative;
    width: 100%;
    height: 310px;
    // background: pink;
    display: flex;
    justify-content: space-between;
    .titrle_wrap {
      position: absolute;
      height: 20px;
      // background: pink;
      width: 500px;
      left: 10%;
      top: 0;
      display: flex;
      justify-content: center;
      div {
        display: flex;
        align-items: center;
        margin-right: 35px;
        span {
          font-size: 12px;
        }
        .item {
          border-radius: 50%;
          width: 10px;
          height: 10px;
          margin-right: 5px;
        }
        .color_1 {
          background-color: #017aff;
        }
        .color_2 {
          background-color: #67afff;
        }
        .color_3 {
          background-color: #f19149;
        }
      }
    }
    .rate_wrap {
      position: absolute;
      height: 50px;
      left: 0%;
      top: 90px;
      width: 800px;
      .item_1 {
        width: 100px;
        margin-right: 25px;
        text-align: center;
        margin: 0 auto;
      }
      .rate_item_wrap {
        display: flex;
        justify-content: space-evenly;
        // background-color: chartreuse;
        .rate_item {
          width: 100px;
          text-align: center;
          // background-color: rgb(255, 0, 0);
        }
        .item_2 {
          margin-right: 35px;
        }
        .item_4 {
          margin-left: 25px;
          // margin-right: 30px;
        }
        .item_6 {
          margin-right: 20px;
        }
      }
      .rate {
        font-size: 14px;
        color: #f19149;
        margin: 0 auto;
      }
      .rate_1 {
        width: 15px;
        height: 15px;
        margin: 0 auto;
        border-radius: 50%;
        background-color: #f19149;
      }
    }
    .leap {
      position: absolute;
      left: 100px;
      width: 50px;
      height: 40px;
      text-align: center;
      // background-color: #017aff;
      p {
        font-size: 14px;
        color: #f19149;
      }
      .color_4 {
        margin-top: 5px;
        border-radius: 50%;
        width: 15px;
        height: 15px;
        margin-left: 18px;
        background-color: #f19149;
      }
    }
    .span_1 {
      position: absolute;
      border-radius: 50%;
      // left: ;
      // bottom: 19%;
      width: 15px;
      height: 15px;
      margin-right: 5px;
      background-color: #f19149;
    }
    // .color_4 {
    //   position: absolute;
    //   border-radius: 50%;
    //   // left: ;
    //   // bottom: 19%;
    //   width: 15px;
    //   height: 15px;
    //   margin-right: 5px;
    //   background-color: #f19149;
    // }
    .first {
      width: 50%;
      height: 100%;
    }
  }
}
</style>
